package com.neudu.glsb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neudu.glsb.commons.JSONReturn;
import com.neudu.glsb.pojo.*;
import com.neudu.glsb.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class ProductsController {

    @Autowired
    private ProductsService productService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private IceLevelService iceLevelService;
    @Autowired
    private SweetnessService sweetnessService;
    @Autowired
    private ProductIngredientService productIngredientService;
    @Autowired
    private ProductIngredientsService productIngredientsService;
    @Autowired
    private IngredientsService ingredientsService;
    @Autowired
    private JSONReturn jsonReturn;
    @Autowired
    private StockService stockService;

    @PostMapping("get_all_products")
    public String getAll(@RequestBody Map<String, Object> pageInfoMap) {
        try {
            Integer pageNum = (Integer) pageInfoMap.get("pageNum");
            Integer pageSize = (Integer) pageInfoMap.get("pageSize");
            String productCategory = (String) pageInfoMap.get("productCategory");
            System.out.println("接收到的参数 - 页码: " + pageNum + ", 页大小: " + pageSize + ", 商品分类: " + productCategory);
            PageHelper.startPage(pageNum, pageSize);
            LambdaQueryWrapper<Products> queryWrapper = new LambdaQueryWrapper<>();
            // 1. 始终只给前台展示“可用”商品
            queryWrapper.eq(Products::getIsAvailable, 1);
            if (!ObjectUtils.isEmpty(productCategory)) {
                queryWrapper.eq(Products::getProductCategory, productCategory);
            }
            List<Products> list = productService.list(queryWrapper);
            PageInfo<Products> pageInfoReturn = new PageInfo<>(list);
            return jsonReturn.returnSuccess(pageInfoReturn);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @PostMapping("get_product_by")
    public String getByCondition(@RequestBody Map<String, Object> conditionMap) {
        try {
            Integer pageNum = (Integer) conditionMap.get("pageNum");
            Integer pageSize = (Integer) conditionMap.get("pageSize");
            String productName = (String) conditionMap.get("productName");

            PageHelper.startPage(pageNum, pageSize);
            LambdaQueryWrapper<Products> queryWrapper = new LambdaQueryWrapper<>();
            if (!ObjectUtils.isEmpty(productName)) {
                queryWrapper.like(Products::getProductName, productName);
            }

            List<Products> products = productService.list(queryWrapper);
            PageInfo<Products> pageInfo = new PageInfo<>(products);
            return jsonReturn.returnSuccess(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @PostMapping("add_one_product")
    public String addOne(@RequestBody Products product) {
        try {
            productService.save(product);
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @PostMapping("getproductby_id")
    public String getById(@RequestBody Map<String, Integer> idMap) {
        try {
            Integer id = idMap.get("id");
            if (ObjectUtils.isEmpty(id)) {
                return jsonReturn.returnError("ID不能为空");
            }
            Products product = productService.getById(id);
            return jsonReturn.returnSuccess(product);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @PostMapping("modifyproductby_id")
    public String modifyById(@RequestBody Products product) {
        try {
            if (ObjectUtils.isEmpty(product.getId())) {
                return jsonReturn.returnError("更新失败，id 不能为空");
            }
            boolean success = productService.updateById(product);
            if (success) {
                return jsonReturn.returnSuccess();
            } else {
                return jsonReturn.returnError("更新失败，未找到对应的产品信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @PostMapping("/shelfOff")
    public String shelfOff(@RequestBody Map<String, Integer> p) {
        try {
            Integer id = p.get("id");
            if (ObjectUtils.isEmpty(id)) return jsonReturn.returnError("ID不能为空");
            boolean ok = productService.lambdaUpdate()
                    .set(Products::getIsAvailable, 0)
                    .eq(Products::getId, id)
                    .update();
            return ok ? jsonReturn.returnSuccess() : jsonReturn.returnFailed("下架失败");
        } catch (JsonProcessingException e) {
            return jsonReturn.returnError("JSON转换异常");
        }
    }

    // 添加商品到购物车
    @PostMapping("addToCart")
    public String addToCart(@RequestBody ShoppingCart shoppingCart) {
        try {
            boolean success = shoppingCartService.save(shoppingCart);
            if (success) {
                return jsonReturn.returnSuccess();
            } else {
                return jsonReturn.returnError("添加到购物车失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    //获取商品种类
    @GetMapping("getAllCategories")
    public String getAllCategories() {
        try {
            // 创建一个 LambdaQueryWrapper 对象，用于构建查询条件
            LambdaQueryWrapper<Products> queryWrapper = new LambdaQueryWrapper<>();
            // 只查询商品分类字段
            queryWrapper.select(Products::getProductCategory);
            // 执行查询，获取所有商品的分类信息
            List<Products> products = productService.list(queryWrapper);
            // 使用 Set 集合来存储分类，Set 会自动去重
            Set<String> categorySet = new HashSet<>();
            // 遍历查询结果，将每个商品的分类添加到 Set 集合中
            for (Products product : products) {
                if (!ObjectUtils.isEmpty(product.getProductCategory())) {
                    categorySet.add(product.getProductCategory());
                }
            }
            // 将 Set 集合转换为 List 集合
            List<String> categories = new ArrayList<>(categorySet);
            // 返回成功响应，包含所有去重后的商品分类
            return jsonReturn.returnSuccess(categories);
        } catch (Exception e) {
            e.printStackTrace();
            // 如果出现异常，返回错误响应
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @PostMapping("addToCartBatch")
    public String addToCartBatch(@RequestBody List<ShoppingCart> shoppingCarts) {
        try {
            for (ShoppingCart cartItem : shoppingCarts) {
                if (ObjectUtils.isEmpty(cartItem.getUserId()) || ObjectUtils.isEmpty(cartItem.getProductId()) || cartItem.getQuantity() <= 0) {
                    return jsonReturn.returnError("购物车项信息不完整");
                }
            }
            boolean success = shoppingCartService.saveBatch(shoppingCarts);
            if (success) {
                return jsonReturn.returnSuccess("批量添加到购物车成功");
            } else {
                return jsonReturn.returnError("批量添加到购物车失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    // 新增：获取所有甜度选项
    @GetMapping("getAllSweetness")
    public String getAllSweetness() {
        try {
            List<Sweetness> list = sweetnessService.listAll();
            return jsonReturn.returnSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    // 新增：获取所有冰量选项
    @GetMapping("getAllIceLevel")
    public String getAllIceLevel() {
        try {
            List<IceLevel> list = iceLevelService.listAll();
            return jsonReturn.returnSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    // 新增：根据商品ID获取关联的小料
    @PostMapping("getIngredientsByProductId")//出错
    public String getIngredientsByProductId(@RequestBody Map<String, Integer> param) {
        try {
            Integer productId = param.get("productId");
            if (ObjectUtils.isEmpty(productId)) {
                return jsonReturn.returnError("商品ID不能为空");
            }
            List<Map<String, Object>> ingredients = productIngredientService.getIngredientsByProductId(productId);
            return jsonReturn.returnSuccess(ingredients);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @PostMapping("loadAssignIngredientData")
    public String loadAssignIngredientData(@RequestBody Map<String, Integer> param) {
        try {
            Integer productId = param.get("productId");
            // 参数校验
            if (ObjectUtils.isEmpty(productId)) {
                return jsonReturn.returnError("商品ID不能为空");
            }

            // 1. 获取已关联的小料
            List<Map<String, Object>> assignedIngredients = productIngredientService.getIngredientsByProductId(productId);
            // 2. 获取可选的小料（未关联的“小料”类型）
            List<Map<String, Object>> optionalIngredients = productIngredientService.getOptionalIngredients(productId);

            // 组装返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("assignedIngredients", assignedIngredients);
            result.put("optionalIngredients", optionalIngredients);

            return jsonReturn.returnSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("加载小料数据失败：" + e.getMessage());
        }
    }


    @PostMapping("submitAssignIngredients")
    public String submitAssignIngredients(@RequestBody Map<String, Object> param) {
        try {
            Integer productId = (Integer) param.get("productId");
            List<Map<String, Object>> maps =
                    (List<Map<String, Object>>) param.get("newIngredients");

            List<ProductIngredient> list = maps.stream()
                    .map(m -> {
                        ProductIngredient pi = new ProductIngredient();
                        pi.setProductId(productId);
                        pi.setIngredientId((Integer) m.get("ingredientId"));
                        pi.setExtraPrice(new BigDecimal(m.get("extraPrice").toString()));
                        pi.setIsDefault((Integer) m.get("isDefault"));
                        return pi;
                    })
                    .collect(Collectors.toList());

            boolean ok = productIngredientService.assignIngredients(productId, list);
            return ok ? jsonReturn.returnSuccess("小料分配成功")
                    : jsonReturn.returnError("小料分配失败");
        } catch (JsonProcessingException e) {
            // 受检异常必须捕获
            e.printStackTrace();
            return jsonReturn.returnError("JSON转换异常");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("提交小料分配失败：" + e.getMessage());
        }
    }

    /**
     * 单条删除小料
     * POST  {"productId":1,"ingredientId":125}
     */
    @PostMapping("removeOneIngredient")
    public String removeOneIngredient(@RequestBody Map<String, Integer> param) {
        try {
            Integer productId = param.get("productId");
            Integer ingredientId = param.get("ingredientId");
            if (ObjectUtils.isEmpty(productId) || ObjectUtils.isEmpty(ingredientId)) {
                return jsonReturn.returnError("参数缺失");
            }
            int rows = productIngredientService.removeOneIngredient(productId, ingredientId);
            return rows > 0 ? jsonReturn.returnSuccess("移除成功")
                    : jsonReturn.returnError("移除失败，可能已不存在");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("删除小料异常：" + e.getMessage());
        }
    }

    //    @PostMapping("createOrder")
//    public String createOrder(@RequestBody Orders order) {
//        try {
//            // 1. 校验参数
//            if (order.getUserId() == null
//                    || order.getPaymentMethod() == null
//                    || order.getOrderProducts() == null
//                    || order.getOrderProducts().isEmpty()) {
//                return jsonReturn.returnError("订单参数不完整");
//            }
//
//            // 2. 计算总金额并构建订单备注
//            BigDecimal totalAmount = BigDecimal.ZERO;
//            StringBuilder remark = new StringBuilder();
//
//            for (Map<String, Object> productMap : order.getOrderProducts()) {
//                // 从Map中提取商品信息（强制类型转换）
//                Integer productId = (Integer) productMap.get("productId");
//                String productName = (String) productMap.get("productName");
//                Integer quantity = (Integer) productMap.get("quantity");
//                BigDecimal price = new BigDecimal(productMap.get("price").toString());
//
//                // 校验商品必填项
//                if (productId == null || quantity == null || price == null || quantity <= 0) {
//                    return jsonReturn.returnError("商品信息不完整：" + productName);
//                }
//
//                // 提取个性化选项
//                String sweetnessName = (String) productMap.get("sweetnessName");
//                String iceName = (String) productMap.get("iceName");
//                List<Map<String, Object>> ingredients = (List<Map<String, Object>>) productMap.get("selectedIngredients");
//
//                // 计算商品基础金额
//                BigDecimal baseAmount = price.multiply(new BigDecimal(quantity));
//
//                // 计算小料总加价
//                BigDecimal ingredientAmount = BigDecimal.ZERO;
//                if (ingredients != null) {
//                    for (Map<String, Object> ing : ingredients) {
//                        BigDecimal extraPrice = new BigDecimal(ing.get("extraPrice").toString());
//                        ingredientAmount = ingredientAmount.add(extraPrice);
//                    }
//                }
//                BigDecimal itemTotal = baseAmount.add(ingredientAmount.multiply(new BigDecimal(quantity)));
//                totalAmount = totalAmount.add(itemTotal);
//
//                // 构建订单备注（例如：珍珠奶茶-2-五分糖-少冰+珍珠+椰果）
//                remark.append(productName).append("-")
//                        .append(quantity).append("-")
//                        .append(sweetnessName).append("-")
//                        .append(iceName);
//
//                // 追加小料信息
//                if (ingredients != null && !ingredients.isEmpty()) {
//                    remark.append("+");
//                    for (Map<String, Object> ing : ingredients) {
//                        remark.append(ing.get("ingredientName")).append("+");
//                    }
//                    remark.setLength(remark.length() - 1); // 移除最后一个"+"
//                }
//                remark.append(";");
//            }
//
//            // 3. 设置订单信息
//            order.setTotalAmount(totalAmount);
//            order.setOrderStatus("制作中");
//            order.setOrderTime(new Date());
//            order.setRemark(remark.toString()); // 保存备注信息
//
//            // 4. 保存订单
//            boolean success = ordersService.save(order);
//            if (success) {
//                return jsonReturn.returnSuccess("订单生成成功");
//            } else {
//                return jsonReturn.returnError("订单生成失败");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return jsonReturn.returnError("创建订单失败：" + e.getMessage());
//        }
//    }
    @PostMapping("createOrder")
    public String createOrder(@RequestBody Orders order) {
        try {
            // 参数校验
            if (order.getUserId() == null || order.getPaymentMethod() == null ||
                    order.getOrderProducts() == null || order.getOrderProducts().isEmpty()) {
                return jsonReturn.returnError("订单参数不完整");
            }

            // 计算总金额并构建备注
            BigDecimal totalAmount = BigDecimal.ZERO;
            StringBuilder remark = new StringBuilder();

            for (Map<String, Object> productMap : order.getOrderProducts()) {
                Integer productId = (Integer) productMap.get("productId");
                String productName = (String) productMap.get("productName");
                Integer quantity = (Integer) productMap.get("quantity");
                BigDecimal price = new BigDecimal(productMap.get("price").toString());
                String sweetnessCode = (String) productMap.get("sweetnessCode"); // 新增：甜度编码
                String iceCode = (String) productMap.get("iceCode"); // 新增：冰度编码
                List<Map<String, Object>> ingredients = (List<Map<String, Object>>) productMap.get("selectedIngredients");

                // 校验基础原料（含甜度/冰度）
                String baseStockMsg = stockService.checkBaseMaterialStock(productId, quantity, sweetnessCode, iceCode);
                if (baseStockMsg != null) {
                    return jsonReturn.returnError(baseStockMsg);
                }

                // 校验小料
                String toppingStockMsg = stockService.checkToppingStock(ingredients, quantity);
                if (toppingStockMsg != null) {
                    return jsonReturn.returnError(toppingStockMsg);
                }

                // 计算金额
                BigDecimal baseAmount = price.multiply(new BigDecimal(quantity));
                BigDecimal ingredientAmount = ingredients.stream()
                        .filter(ing -> (Integer) ing.get("ingredientId") != -1)
                        .map(ing -> new BigDecimal(ing.get("extraPrice").toString()))
                        .reduce(BigDecimal.ZERO, BigDecimal::add)
                        .multiply(new BigDecimal(quantity));
                totalAmount = totalAmount.add(baseAmount).add(ingredientAmount);

                // 构建备注
                remark.append(productName).append("-").append(quantity)
                        .append("-").append(productMap.get("sweetnessName"))
                        .append("-").append(productMap.get("iceName"));
                if (ingredients != null && !ingredients.isEmpty()) {
                    remark.append("+").append(ingredients.stream()
                            .filter(ing -> (Integer) ing.get("ingredientId") != -1)
                            .map(ing -> ing.get("ingredientName").toString())
                            .collect(Collectors.joining("+")));
                }
                remark.append(";");
            }

            // 保存订单
            order.setTotalAmount(totalAmount);
            order.setOrderStatus("制作中");
            order.setOrderTime(new Date());
            order.setRemark(remark.toString());

            // 扣减库存
            for (Map<String, Object> productMap : order.getOrderProducts()) {
                Integer productId = (Integer) productMap.get("productId");
                Integer quantity = (Integer) productMap.get("quantity");
                String sweetnessCode = (String) productMap.get("sweetnessCode");
                String iceCode = (String) productMap.get("iceCode");
                List<Map<String, Object>> ingredients = (List<Map<String, Object>>) productMap.get("selectedIngredients");

                stockService.deductBaseMaterialStock(productId, quantity, sweetnessCode, iceCode);
                stockService.deductToppingStock(ingredients, quantity);
            }

            ordersService.save(order);
            return jsonReturn.returnSuccess("订单生成成功");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("创建订单失败：" + e.getMessage());
        }
    }
    //新增
// 在ProductsController中新增
    @PostMapping("loadAssignBasePackageMaterials")
    public String loadAssignBasePackageMaterials(@RequestBody Map<String, Integer> param) {
        try {
            Integer productId = param.get("productId");
            if (ObjectUtils.isEmpty(productId)) {
                return jsonReturn.returnError("商品ID不能为空");
            }
            Map<String, Object> data = productIngredientsService.loadBasePackageMaterialData(productId);
            return jsonReturn.returnSuccess(data);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("加载材料数据失败：" + e.getMessage());
        }
    }

    @PostMapping("submitAssignBasePackageMaterials")
    public String submitAssignBasePackageMaterials(@RequestBody Map<String, Object> param) {
        try {
            Integer productId = (Integer) param.get("productId");
            List<Map<String, Object>> maps = (List<Map<String, Object>>) param.get("materials");

            // 参数校验
            if (ObjectUtils.isEmpty(productId)) {
                return jsonReturn.returnError("商品ID不能为空");
            }
            if (ObjectUtils.isEmpty(maps)) {
                // 允许空提交（清空所有材料关联）
                productIngredientsService.submitBasePackageMaterials(productId, new ArrayList<>());
                return jsonReturn.returnSuccess("材料分配已清空");
            }

            // 转换为实体列表（包含用量信息）
            List<ProductIngredients> materials = maps.stream()
                    .map(m -> {
                        ProductIngredients pi = new ProductIngredients();
                        pi.setProductId(productId);
                        pi.setIngredientId((Integer) m.get("ingredientId"));
                        pi.setExtraPrice(new BigDecimal(m.get("extraPrice").toString()));
                        pi.setIsDefault((Integer) m.get("isDefault"));
                        // 关键：设置单份商品所需材料的用量
                        pi.setQuantityNeeded(new BigDecimal(m.get("quantityNeeded").toString()));
                        return pi;
                    })
                    .collect(Collectors.toList());

            // 执行保存（先删除旧关联，再插入新关联）
            boolean success = productIngredientsService.submitBasePackageMaterials(productId, materials);
            return success ? jsonReturn.returnSuccess("材料分配成功")
                    : jsonReturn.returnError("材料分配失败");
        } catch (NumberFormatException e) {
            return jsonReturn.returnError("数据格式错误：请检查用量或价格是否为有效数字");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("提交材料分配失败：" + e.getMessage());
        }
    }

    @PostMapping("removeBasePackageMaterial")
    public String removeBasePackageMaterial(@RequestBody Map<String, Integer> param) {
        try {
            Integer productId = param.get("productId");
            Integer ingredientId = param.get("ingredientId");

            // 参数校验
            if (ObjectUtils.isEmpty(productId)) {
                return jsonReturn.returnError("商品ID不能为空");
            }
            if (ObjectUtils.isEmpty(ingredientId)) {
                return jsonReturn.returnError("材料ID不能为空");
            }

            // 执行移除（仅移除基础原料/包装材料的关联）
            int rows = productIngredientsService.removeBasePackageMaterial(productId, ingredientId);
            if (rows > 0) {
                return jsonReturn.returnSuccess("材料移除成功");
            } else {
                return jsonReturn.returnError("移除失败：未找到对应的材料关联记录");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("移除材料异常：" + e.getMessage());
        }
    }
    @PostMapping("getIngredientStock")
    public String getIngredientStock(@RequestBody Map<String, Integer> param) {
        try {
            Integer ingredientId = param.get("ingredientId");
            if (ObjectUtils.isEmpty(ingredientId)) {
                return jsonReturn.returnError("原料ID不能为空");
            }
            Ingredients ingredient = ingredientsService.getById(ingredientId);
            if (ingredient == null) {
                return jsonReturn.returnError("原料不存在");
            }
            return jsonReturn.returnSuccess(ingredient);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("查询库存失败：" + e.getMessage());
        }
    }
}